import subprocess
import os
from multiprocessing import Pool
from Params import configs  # 导入配置


def compile_model_with_jmodelica(jmodelica_path, python_script_path, model_name, jvm_args, fmu_res):
    batch_script_path = "run_jmodelica.bat"  # 修改为批处理脚本的路径
    try:
        # 调用批处理脚本，传递 Python 脚本路径，模型名称和 JVM 参数
        subprocess.run([batch_script_path, jmodelica_path, python_script_path, model_name, jvm_args, fmu_res],
                       check=True)
        print(f"Successfully compiled model {model_name}")
    except subprocess.CalledProcessError as e:
        print(f"Error compiling model {model_name}: {e}")


def compile_models_with_jmodelica(jmodelica_path, model_names, jvm_args, fmu_res):
    python_script_path = "fmu_build.py"  # 确保路径正确

    # 创建一个进程池，根据系统的核心数来确定进程数量
    with Pool(processes=os.cpu_count()) as pool:
        pool.starmap(compile_model_with_jmodelica,
                     [(jmodelica_path, python_script_path, model_name, jvm_args, fmu_res) for model_name in
                      model_names])


def main():
    # 读取模型列表
    with open('models.txt', 'r') as file:
        model_names = file.read().splitlines()

    jmodelica_path = configs.jmodelica_path
    jvm_args = configs.jvm_args
    fmu_res = configs.fmu_res

    if not os.path.exists(fmu_res):
        os.makedirs(fmu_res)

    # 编译所有模型
    compile_models_with_jmodelica(jmodelica_path, model_names, jvm_args, fmu_res)


if __name__ == '__main__':
    main()
